import request from '@/util/baseHttpServer';
// import moment from 'moment';

const serverPreFix = {
  workbench: '',
  uicore: '/uicore',
};

// const MOCK = '/mock';
const headers = {
  token: '123token',
};

/**
 * get请求
 * @param {String}url 必传参数，指定接口的相对路径
 * @param {Object|{}}data 可选参数，请求参数
 * @returns {Promise<any>}
 * @private
 */
const _get = (url, data = {}, header = false) => new Promise((resolve, reject) => {
  request(url, {
    params: data,
  })
    .then(res => {
      if (header) {
        resolve(res.data);
      } else {
        resolve(res);
      }
    })
    .catch(err => {
      reject(err);
    });
});
/**
 * put请求
 * @param {String}url 必传参数，指定接口的相对路径
 * @param {Object|{}}data 可选参数，请求参数
 * @returns {Promise<any>}
 * @private
 */
const _put = (url, data = {}, header = true) => new Promise((resolve, reject) => {
  request({
    url,
    data, // 发的是错误的
    method: 'put',
  })
    .then(res => {
      if (header) {
        resolve(res.data);
      } else {
        resolve(res);
      }
    })
    .catch(err => {
      reject(err);
    });
});

/**
 * post请求
 * @param {String}url 必传参数，指定接口的相对路径
 * @param {Object|{}}data 可选参数，指定调取接口的参数
 * @param {String}func 可选参数，调用接口的前端模块的名称
 * @param {String}event 可选参数，请求的作用描述
 * @returns {Promise<any>}
 * @private
 */
const _post = function (url, data = {}, func = '', event = '', type) {
  const { token } = window.Vue.$user;
  if (!token) {
    window.Vue.$router.push({
      path: '/login',
      query: {
        redirect: window.Vue.$route.fullPath,
      },
    });
    return new Promise(() => {});
  }

  const contextData = {
    requestId: Math.random()
      .toString(36)
      .substring(7),
    userCode: window.Vue.$user.empno,
    moduleName: window.Vue.$route.path.split('/')[1],
    functionName: func,
    eventName: event,
    // requestTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
    requestIp: '',
  };

  if (typeof data !== 'string') {
    data.requestContextEx = contextData;
  }

  let responseType = 'json';
  if (type === 'download' || type === 'upload') {
    responseType = 'blob';
    headers.ContentType = 'application/json';
  }

  return request({
    url: `/api${url}`,
    data,
    method: 'post',
    responseType,
    headers,
  });
};

export default (url, data, func, event, type) => _post(serverPreFix.workbench + url, data, func, event, type);

export const getRequest = (url, data) => _get(url, data);
export const putRequest = (url, data) => _put(url, data);
